{% extends 'base.html' %}
{% block title %}台风信息{% endblock %}
{% block head %}
    <style>
        /* 添加选中样式 */
        tr.selected {
            opacity: 0.5; /* 降低透明度 */
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.6.0/dist/echarts.min.js"></script>
{% endblock %}
{% block pageName %}台风信息{% endblock %}
{% block main %}
    <div class="row" id="table-data"></div>
    <div class="row">
        <div class="col-md-8">
            <div class="card card-bg">
                <div class="card-body">
                    <h5 class="card-title">图表</h5>
                    <div name="typhoon-table" id="chart"
                         style="width: 600px; height: 400px;margin: 0 auto; display: block;"></div>
                </div>
            </div>
        </div>
        <div class="col-md-4" name="typhoon-list">
            <div class="card card-bg">
                <div class="card-body">
                    <h5 class="card-title" style="display: inline-block; margin-right: 10px;">台风列表</h5>
                    <div class="dropdown" style="display: inline-block; float: right;">
                        <button class="btn btn-primary dropdown-toggle" type="button" id="yearDropdownButton"
                                data-bs-toggle="dropdown" aria-expanded="false">
                            选择年份
                        </button>
                        <ul class="dropdown-menu" aria-labelledby="yearDropdownButton"
                            style="max-height: 200px; overflow-y: auto;">
                            {% for year in years %}
                                <li><a class="dropdown-item" href="#">{{ year }}</a></li>
                            {% endfor %}
                        </ul>
                    </div>
                    <div style="max-height: 400px; overflow-y: auto;">
                        <table class="table" name="typhoon-name">
                            <thead>
                            <tr>
                                <th scope="col" style="position: sticky; top: 0; background-color: #1f1f2b;">中文名</th>
                                <th scope="col" style="position: sticky; top: 0; background-color: #1f1f2b;">英文名</th>
                                <th scope="col" style="position: sticky; top: 0; background-color: #1f1f2b;">是否停止
                                </th>
                            </tr>
                            </thead>
                            <tbody>
                            <!-- 这里的内容将通过 JavaScript 动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-8">
            <div class="card card-bg actions-widget text-center">
                <div class="card-body">
                    <div class="actions-widget-item">
                        <button type="button" class="btn btn-circle text-primary" id="leida"><i
                                class="fas fa-share"></i></button>
                        <span class="actions-widget-item-title">雷达图</span>
                    </div>
                    <div class="actions-widget-item">
                        <button type="button" class="btn btn-circle text-success" id="speed-line"><i
                                class="far fa-credit-card"></i>
                        </button>
                        <span class="actions-widget-item-title">速度散点图</span>
                    </div>
                    <div class="actions-widget-item">
                        <button type="button" class="btn btn-circle text-warning" id="level-line"><i
                                class="fas fa-lock"></i></button>
                        <span class="actions-widget-item-title">等级折线图</span>
                    </div>
                    <div class="actions-widget-item">
                        <button type="button" class="btn btn-circle text-info" id="bar"><i class="fas fa-user-plus"></i>
                        </button>
                        <span class="actions-widget-item-title">压强柱状图</span>
                    </div>
                    <div class="actions-widget-item">
                        <button type="button" class="btn btn-circle text-success" id="bing"><i
                                class="fas fa-calendar"></i>
                        </button>
                        <span class="actions-widget-item-title">强度统计图</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card card-bg text-center">
                <div class="card-body">
                    <div class="">
                        <h5 class="text-white">选择你感兴趣的台风</h5>
                        <p class="m-t-xs" name="typhoon-names">台风名称</p>
                        <a href="#" class="btn btn-success widget-info-action" id="table-button">显示图标</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
{% block footer %}{% endblock %}
{% block js %}
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const dropdownItems = document.querySelectorAll('.dropdown-item');
            const tableBody = document.querySelector('table[name="typhoon-name"] tbody');
            const selectedTyphoons = []; // 存储选中的台风 ID
            const selectedTyphoonNames = []; // 存储选中的台风名称
            const typhoonNamesDisplay = document.querySelector('p[name="typhoon-names"]'); // 获取显示选中台风 ID 的元素
            let chart;

            // 获取最后一年的数据
            function fetchLastYearData() {
                const lastYear = {{ years|last }}; // 获取最后一年的数据
                fetch(`/selected_get_typhoon?year=${lastYear}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status) {
                            tableBody.innerHTML = '';
                            data.data.forEach(typhoon => {
                                const row = `<tr data-id="${typhoon.Typhoon_Id}" data-name="${typhoon.Typhoon_CName}">
                                    <td>${typhoon.Typhoon_CName}</td>
                                    <td>${typhoon.Typhoon_EName}</td>
                                    <td><span class="badge bg-success">${typhoon.Typhoon_StopOrNot}</span></td>
                                </tr>`;
                                tableBody.innerHTML += row;
                            });
                            addRowClickEvents(); // 添加行点击事件
                        } else {
                            alert(data.error);
                        }
                    });
            }

            // 添加行点击事件
            function addRowClickEvents() {
                const rows = tableBody.querySelectorAll('tr');
                rows.forEach(row => {
                    row.addEventListener('click', function () {
                        const typhoonId = this.getAttribute('data-id'); // 获取台风 ID
                        const typhoonName = this.getAttribute('data-name'); // 获取台风名称
                        const index = selectedTyphoons.indexOf(typhoonId);

                        if (index > -1) {
                            // 如果已经选中，取消选中
                            selectedTyphoons.splice(index, 1);
                            selectedTyphoonNames.splice(index, 1); // 同时移除名称
                            this.classList.remove('selected'); // 移除选中样式
                        } else {
                            // 如果未选中，添加到选中列表
                            if (selectedTyphoons.length < 3) {
                                selectedTyphoons.push(typhoonId);
                                selectedTyphoonNames.push(typhoonName); // 添加名称
                            } else {
                                // 超过三个，移除最前面的一个
                                const removedTyphoonId = selectedTyphoons.shift(); // 移除第一个
                                const removedTyphoonName = selectedTyphoonNames.shift(); // 移除对应名称
                                // 找到被移除的行并恢复其状态
                                const removedRow = Array.from(rows).find(r => r.getAttribute('data-id') === removedTyphoonId);
                                if (removedRow) {
                                    removedRow.classList.remove('selected'); // 恢复之前的状态
                                }
                                selectedTyphoons.push(typhoonId); // 添加新的
                                selectedTyphoonNames.push(typhoonName); // 添加新的名称
                            }
                            this.classList.add('selected'); // 添加选中样式
                        }
                        updateSelectedTyphoonNames(); // 更新显示
                    });
                });
            }

            // 更新显示选中的台风名称
            function updateSelectedTyphoonNames() {
                typhoonNamesDisplay.innerText = selectedTyphoonNames.join(', '); // 显示名称而不是 ID
            }

            // 调用函数以获取最后一年的数据
            fetchLastYearData();

            dropdownItems.forEach(item => {
                item.addEventListener('click', function (event) {
                    const selectedYear = event.target.innerText;
                    fetch(`/selected_get_typhoon?year=${selectedYear}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.status) {
                                tableBody.innerHTML = '';
                                data.data.forEach(typhoon => {
                                    const row = `<tr data-id="${typhoon.Typhoon_Id}" data-name="${typhoon.Typhoon_CName}">
                                        <td>${typhoon.Typhoon_CName}</td>
                                        <td>${typhoon.Typhoon_EName}</td>
                                        <td><span class="badge bg-success">${typhoon.Typhoon_StopOrNot}</span></td>
                                    </tr>`;
                                    tableBody.innerHTML += row;
                                });
                                addRowClickEvents(); // 添加行点击事件
                            } else {
                                alert(data.error);
                            }
                        });
                });
            });

            function fetchTyphoonData(Chart) {
                console.log('Selected Typhoons:', selectedTyphoons);
                $.ajax({
                    url: '/get_typhoon_data/',
                    data: {
                        'typhoon_ids': selectedTyphoons.join(',')
                    },
                    dataType: 'json',
                    success: function (response) {
                        const typhoonData = response.data;

                        // 如果没有数据，返回并停止执行
                        if (!typhoonData || typhoonData.length === 0) {
                            console.error('没有获取到台风数据');
                            alert('至少选择一个台风');
                            return;
                        }

                        Chart(typhoonData)
                    },
                    error: function (xhr, status, error) {
                        console.error('请求失败:', error);
                    }
                });
            }

            function drawRadarChart(typhoonData) {
    if (chart) {
        chart.dispose();  // 释放旧的实例
    }
    // 初始化 ECharts 实例
    chart = echarts.init(document.getElementById('chart'));

    // 设置雷达图指标
    const indicators = [
        {name: '平均风速 (km/h)', max: 60},
        {name: '平均压强 (hPa)', max: 1050},
        {name: '最大等级', max: 20},
        {name: '路径点数', max: 150},
        {name: '持续时间 (天)', max: 20}
    ];

    // 准备雷达图的数据项
    const seriesData = typhoonData.map(data => ({
        value: [
            data.avg_wind_speed,
            data.avg_pressure,
            data.max_level,
            data.path_point_count,
            data.duration_days
        ],
        name: data.typhoon_name
    }));

    // 配置雷达图的参数
    const option = {
        title: {
            text: '台风数据雷达图',
            textStyle: {
                color: '#fff' // 设置标题颜色为白色
            }
        },
        tooltip: {},
        legend: {
            data: typhoonData.map(data => data.typhoon_name),
            textStyle: {
                color: '#fff' // 设置图例文字颜色为白色
            }
        },
        radar: {
            indicator: indicators
        },
        series: [{
            type: 'radar',
            data: seriesData
        }]
    };

    // 使用配置项和数据显示图表
    chart.setOption(option);

    // 生成表格并插入到 #table-data 容器
    let tableHTML = `
    <table class="table table-striped" style="width: 100%; text-align: center;">
        <thead>
            <tr>
                <th>台风名称</th>
                <th>平均风速 (km/h)</th>
                <th>平均压强 (hPa)</th>
                <th>最大等级</th>
                <th>路径点数</th>
                <th>持续时间 (天)</th>
            </tr>
        </thead>
        <tbody>
    `;

    // 将台风数据填充到表格中
    typhoonData.forEach(data => {
        tableHTML += `
        <tr>
            <td>${data.typhoon_name}</td>
            <td>${data.avg_wind_speed}</td>
            <td>${data.avg_pressure}</td>
            <td>${data.max_level}</td>
            <td>${data.path_point_count}</td>
            <td>${data.duration_days}</td>
        </tr>
    `;
    });

    // 关闭表格标签
    tableHTML += `
        </tbody>
    </table>
    `;

    // 将表格插入到 #table-data 容器中
    document.getElementById('table-data').innerHTML = tableHTML;
}

            document.getElementById('table-button').addEventListener('click', function (event) {
                event.preventDefault();  // 阻止默认的链接跳转
                fetchTyphoonData(drawRadarChart);  // 调用fetchTyphoonData函数
            });
            document.getElementById('leida').addEventListener('click', function (event) {
                event.preventDefault();  // 阻止默认的链接跳转
                fetchTyphoonData(drawRadarChart);  // 调用fetchTyphoonData函数
            });

            function fetchTyphoonData2(Chart) {
                console.log('Selected Typhoons:', selectedTyphoons);
                $.ajax({
                    url: '/get_typhoon_data_table/',
                    data: {
                        'typhoon_ids': selectedTyphoons.join(',')
                    },
                    dataType: 'json',
                    success: function (response) {
                        const typhoonData = response.data;

                        // 如果没有数据，返回并停止执行
                        if (!typhoonData || typhoonData.length === 0) {
                            console.error('没有获取到台风数据');
                            alert('至少选择一个台风');
                            return;
                        }
                        console.log(typhoonData)

                        Chart(typhoonData)
                    },
                    error: function (xhr, status, error) {
                        console.error('请求失败:', error);
                    }
                });
            }

            function drawSpeedChart(typhoonData) {
    if (chart) {
        chart.dispose();  // 释放旧的实例
    }
    chart = echarts.init(document.getElementById('chart'));

    // 准备数据
    const seriesData = [];
    const legendData = [];
    let times;

    // 遍历台风数据
    typhoonData.forEach((typhoon) => {
        const speeds = typhoon.wind_speeds; // 假设wind_speeds是数组，包括不同时间点的台风风速
        if (!times) {
            times = [...Array(speeds.length).keys()].map(i => `T${i + 1}`); // 使用实际时间数据替换
        } // 模拟时间点，可以替换为您的实际时间数据

        // 将数据添加到系列，修改为scatter
        seriesData.push({
            name: typhoon.typhoon_name,  // 使用台风的ID作为系列名称
            type: 'scatter',  // 更改为散点图类型
            data: speeds.map((speed, index) => [times[index], speed])  // 格式化为[x, y]形式
        });

        legendData.push(typhoon.typhoon_name);
    });

    // ECharts 配置
    const option = {
        title: {
            text: '台风风速变化散点图',
            textStyle: {
                color: '#fff' // 设置标题颜色为白色
            }
        },
        tooltip: {
            trigger: 'item',  // 设置为'item'以便触发每个数据点的提示框
            formatter: function (params) {
                return `${params.seriesName}<br/>时间: ${params.data[0]}<br/>风速: ${params.data[1]} km/h`; // 格式化tooltip
            }
        },
        legend: {
            data: legendData,
            textStyle: {
                color: '#fff' // 设置图例文字颜色为白色
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: times // X轴数据
        },
        yAxis: {
            type: 'value',
            name: '风速 (km/h)' // 根据实际单位替换，假设风速单位为km/h
        },
        series: seriesData
    };

    // 使用制定的配置项和数据显示图表
    chart.setOption(option);

    // 生成表格并插入到 #table-data 容器
    let tableHTML = `
    <table class="table table-striped" style="width: 100%; text-align: center;">
        <thead>
            <tr>
                <th>台风名称</th>
                <th>最高风速 (km/h)</th>
                <th>最低风速 (km/h)</th>
                <th>平均风速 (km/h)</th>
            </tr>
        </thead>
        <tbody>
    `;

    // 遍历台风数据生成表格内容
    typhoonData.forEach(typhoon => {
        const speeds = typhoon.wind_speeds;
        const maxSpeed = Math.max(...speeds);  // 计算最高风速
        const minSpeed = Math.min(...speeds);  // 计算最低风速
        const avgSpeed = speeds.reduce((sum, speed) => sum + speed, 0) / speeds.length;  // 计算平均风速

        tableHTML += `
        <tr>
            <td>${typhoon.typhoon_name}</td>
            <td>${maxSpeed}</td>
            <td>${minSpeed}</td>
            <td>${avgSpeed.toFixed(2)}</td> <!-- 保留两位小数 -->
        </tr>
    `;
    });

    // 关闭表格标签
    tableHTML += `
        </tbody>
    </table>
    `;

    // 将表格插入到 #table-data 容器中
    document.getElementById('table-data').innerHTML = tableHTML;
}

            function drawLevelChart(typhoonData) {
    if (chart) {
        chart.dispose();  // 释放旧的实例
    }
    chart = echarts.init(document.getElementById('chart'));

    // 准备数据
    const seriesData = [];
    const legendData = [];
    let times;

    // 遍历台风数据
    typhoonData.forEach((typhoon) => {
        const levels = typhoon.levels; // 假设levels是数组，包括不同时间点的台风等级
        if (!times) {
            times = [...Array(levels.length).keys()].map(i => `T${i + 1}`); // 使用实际时间数据替换
        }

        // 将数据添加到系列
        seriesData.push({
            name: typhoon.typhoon_name,  // 使用台风的名称作为系列名称
            type: 'line',
            data: levels
        });

        legendData.push(typhoon.typhoon_name);
    });

    // ECharts 配置
    const option = {
        title: {
            text: '台风等级变化图',
            textStyle: {
                color: '#fff' // 设置标题颜色为白色
            }
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: legendData,
            textStyle: {
                color: '#fff' // 设置图例文字颜色为白色
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: times // X轴数据
        },
        yAxis: {
            type: 'value',
            name: '台风等级' // 假设台风等级是某种数值，可以根据实际需要替换
        },
        series: seriesData
    };

    // 使用制定的配置项和数据显示图表
    chart.setOption(option);

    // 生成表格并插入到 #table-data 容器
    let tableHTML = `
    <table class="table table-striped" style="width: 100%; text-align: center;">
        <thead>
            <tr>
                <th>台风名称</th>
                <th>最高等级</th>
                <th>最低等级</th>
                <th>普遍等级</th>
            </tr>
        </thead>
        <tbody>
    `;

    // 遍历台风数据生成表格内容
    typhoonData.forEach(typhoon => {
        const levels = typhoon.levels;
        const maxLevel = Math.max(...levels);  // 计算最高等级
        const minLevel = Math.min(...levels);  // 计算最低等级
        const modeLevel = getMode(levels);  // 计算众数

        tableHTML += `
        <tr>
            <td>${typhoon.typhoon_name}</td>
            <td>${maxLevel}</td>
            <td>${minLevel}</td>
            <td>${modeLevel}</td> <!-- 显示众数 -->
        </tr>
    `;
    });

    // 关闭表格标签
    tableHTML += `
        </tbody>
    </table>
    `;

    // 将表格插入到 #table-data 容器中
    document.getElementById('table-data').innerHTML = tableHTML;
}
            
            // 计算众数的函数
            function getMode(arr) {
                const frequency = {};
                let maxFreq = 0;
                let mode = null;

                // 统计每个等级出现的频率
                arr.forEach((value) => {
                    frequency[value] = (frequency[value] || 0) + 1;
                    if (frequency[value] > maxFreq) {
                        maxFreq = frequency[value];
                        mode = value;
                    }
                });

                return mode;
            }


            function drawPressureChart(typhoonData) {
    if (chart) {
        chart.dispose();  // 释放旧的实例
    }
    chart = echarts.init(document.getElementById('chart'));

    // 准备数据
    const seriesData = [
        {name: '最大压强', type: 'bar', data: []},
        {name: '最小压强', type: 'bar', data: []},
        {name: '平均压强', type: 'bar', data: []}
    ];
    const legendData = ['最大压强', '最小压强', '平均压强'];
    const typhoonNames = [];

    // 遍历台风数据
    typhoonData.forEach((typhoon) => {
        typhoonNames.push(typhoon.typhoon_name); // 添加台风名称
        seriesData[0].data.push(typhoon.max_pressure); // 最大压强
        seriesData[1].data.push(typhoon.min_pressure); // 最小压强
        seriesData[2].data.push(typhoon.avg_pressure); // 平均压强
    });

    // ECharts 配置
    const option = {
        title: {
            text: '台风压强柱形图',
            textStyle: {
                color: '#fff', // 设置标题颜色为白色
            }
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: legendData,
            textStyle: {
                color: '#fff', // 设置图例文字颜色为白色
            }
        },
        xAxis: {
            type: 'category',
            data: typhoonNames // X轴为台风名称
        },
        yAxis: {
            type: 'value',
            name: '压强 (hPa)' // 假设单位为hPa
        },
        series: seriesData
    };

    // 使用制定的配置项和数据显示图表
    chart.setOption(option);

    // 生成表格并插入到 #table-data 容器
    let tableHTML = `
    <table class="table table-striped" style="width: 100%; text-align: center;">
        <thead>
            <tr>
                <th>台风名称</th>
                <th>最高压强 (hPa)</th>
                <th>最低压强 (hPa)</th>
                <th>平均压强 (hPa)</th>
            </tr>
        </thead>
        <tbody>
    `;

    // 遍历台风数据生成表格内容
    typhoonData.forEach(typhoon => {
        tableHTML += `
        <tr>
            <td>${typhoon.typhoon_name}</td>
            <td>${typhoon.max_pressure}</td>
            <td>${typhoon.min_pressure}</td>
            <td>${(typhoon.avg_pressure).toFixed(2)}</td>
        </tr>
    `;
    });

    // 关闭表格标签
    tableHTML += `
        </tbody>
    </table>
    `;

    // 将表格插入到 #table-data 容器中
    document.getElementById('table-data').innerHTML = tableHTML;
}

            function drawBingChart(typhoonData) {
                if (chart) {
                    chart.dispose();  // 释放旧的实例
                }
                chart = echarts.init(document.getElementById('chart'));
                document.getElementById('table-data').innerHTML = '';

                const results = [['Product', 'Sales', 'ID']];
                let id_list = [];
                typhoonData.forEach(typhoon => {
                    const typhoonId = typhoon.typhoon_id;
                    id_list.push(typhoonId);
                    for (const [intensityName, count] of Object.entries(typhoon.intensity_distribution)) {
                        results.push([intensityName, count, typhoonId]);
                    }
                });

                option = {
                    dataset: [
                        {
                            source: results
                        },
                        {
                            transform: {
                                type: 'filter',
                                config: {dimension: 'ID', value: id_list[0]}
                            }
                        },
                        {
                            transform: {
                                type: 'filter',
                                config: {dimension: 'ID', value: id_list[1]}
                            }
                        },
                        {
                            transform: {
                                type: 'filter',
                                config: {dimension: 'ID', value: id_list[2]}
                            }
                        }
                    ],
                    legend: {
                        orient: 'horizontal',
                        left: 'center',
                        top: 'top',
                        textStyle: {
                            color: '#fff',  // 修改这里，设置为白色
                            fontSize: 12
                        }
                    },
                    series: [
                        {
                            name: '台风强度分布 - 台风 1',
                            type: 'pie',
                            radius: 50,
                            center: ['50%', '25%'],
                            datasetIndex: 1,
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        },
                        {
                            name: '台风强度分布 - 台风 2',
                            type: 'pie',
                            radius: 50,
                            center: ['50%', '50%'],
                            datasetIndex: 2,
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        },
                        {
                            name: '台风强度分布 - 台风 3',
                            type: 'pie',
                            radius: 50,
                            center: ['50%', '75%'],
                            datasetIndex: 3,
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ],
                    // Optional. Only for responsive layout:
                    media: [
                        {
                            query: {minAspectRatio: 1},
                            option: {
                                series: [
                                    {center: ['25%', '50%']},
                                    {center: ['50%', '50%']},
                                    {center: ['75%', '50%']}
                                ]
                            }
                        },
                        {
                            option: {
                                series: [
                                    {center: ['50%', '25%']},
                                    {center: ['50%', '50%']},
                                    {center: ['50%', '75%']}
                                ]
                            }
                        }
                    ]
                };

                option && chart.setOption(option);
            }


            document.getElementById('speed-line').addEventListener('click', function (event) {
                event.preventDefault();  // 阻止默认的链接跳转
                fetchTyphoonData2(drawSpeedChart);  // 调用fetchTyphoonData函数
            });
            document.getElementById('level-line').addEventListener('click', function (event) {
                event.preventDefault();  // 阻止默认的链接跳转
                fetchTyphoonData2(drawLevelChart);  // 调用fetchTyphoonData函数
            });
            document.getElementById('bar').addEventListener('click', function (event) {
                event.preventDefault();  // 阻止默认的链接跳转
                fetchTyphoonData2(drawPressureChart);  // 调用fetchTyphoonData函数
            });
            document.getElementById('bing').addEventListener('click', function (event) {
                event.preventDefault();  // 阻止默认的链接跳转
                fetchTyphoonData2(drawBingChart);  // 调用fetchTyphoonData函数
            });
        });

    </script>
{% endblock %}